package softtech.apps.dangtinraovat;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import softtech.apps.model.Product;
import softtech.apps.utilities.HttpRequest;
import softtech.apps.utilities.MultipartEntity;
import softtech.apps.utilities.Utilities;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.Toast;

public class ActivityPostProduct extends Activity{
	
	private static final String TAG = "upload";
	private ProgressDialog pdia;
	String mCurrentPhotoPath;
	private String selectedImagePath;
	static final int REQUEST_TAKE_PHOTO = 1;
	File photoFile = null;
	int current_image_view = 0;
	ProgressBar pgr1,pgr2,pgr3;
	Bitmap[] imageBMP = new Bitmap[3];
	String[] imagePath = new String[3];
	// All Product View
	private ImageView mImageView1,mImageView2,mImageView3;
	private Spinner spColor,spCategory;
	Button btPost;
	EditText edPName,edPSize,edPPrice,edPDescription;
	// product value
	Boolean check = false;
	ArrayAdapter<String> adapterCategory,adapterColor;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_post_product);
		init_view();
		init_event_listener();
		// To do something here
		
	}
	
	public void init_view(){
		// Spinner Category
		String categories[] = { "Dien thoai",
				"Quan ao", 
				"May tinh",
				"Thiet bi gia dung",
				"Nha dat - Bat dong san",
				"Do doc - Do co",
				"Lao dong - viec lam",
				"Dich vu khac" };
		spCategory = (Spinner) findViewById(R.id.SpinnerCategory);
		adapterCategory = new ArrayAdapter<String>(this,
				R.layout.support_simple_spinner_dropdown_item, categories);
		spCategory.setAdapter(adapterCategory);
		// Spinner Color
		String colors[] = { "Xanh",
				"Do", 
				"Tim",
				"Vang",
				"Den",
				"Xam"
				};
		spColor = (Spinner) findViewById(R.id.SpinnerColor);
		adapterColor = new ArrayAdapter<String>(this,
				R.layout.support_simple_spinner_dropdown_item, colors);
		spColor.setAdapter(adapterColor);
		// Progress Bar
		pgr1 = (ProgressBar) findViewById(R.id.progressBar1);
		pgr2 = (ProgressBar) findViewById(R.id.progressBar2);
		pgr3 = (ProgressBar) findViewById(R.id.progressBar3);
		
		// Product's images view
		mImageView1 = (ImageView) findViewById(R.id.imageviewOne);
		mImageView2 = (ImageView) findViewById(R.id.imageviewTwo);
		mImageView3 = (ImageView) findViewById(R.id.imageviewThree);
		
		// Init product's images
		Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.draghere);
		mImageView1.setImageBitmap(bImage);
		mImageView2.setImageBitmap(bImage);
		mImageView3.setImageBitmap(bImage);
		
		edPName = (EditText) findViewById(R.id.edProductName);
		edPSize = (EditText) findViewById(R.id.edProductSize);
		edPPrice = (EditText) findViewById(R.id.edProductPrice);
		edPDescription = (EditText) findViewById(R.id.edProductDescription);
		// Init button post
		btPost = (Button) findViewById(R.id.btPost);
		
	}
	public void init_event_listener(){
		mImageView1.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
            	current_image_view = 0;
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Select Picture"), REQUEST_TAKE_PHOTO);
            }
        });
		
		mImageView2.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
            	current_image_view = 1;
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Select Picture"), REQUEST_TAKE_PHOTO);
            }
        });
		
		mImageView3.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
            	current_image_view = 2;
                Intent intent = new Intent();
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(Intent.createChooser(intent,"Select Picture"), REQUEST_TAKE_PHOTO);
            }
        });
		
		btPost.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				check = true;
				if(check){
					try {
						sendPhoto(imageBMP);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private void takePhoto() {
//		Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
//		intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
//		startActivityForResult(intent, 0);
		dispatchTakePictureIntent();
	}

	@SuppressLint("NewApi")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		Log.i(TAG, "onActivityResult: " + this);
		if (requestCode == REQUEST_TAKE_PHOTO && resultCode == Activity.RESULT_OK && data != null) {
			Log.d(TAG, "Current image = "+current_image_view);
			 Uri selectedImageUri = data.getData();
             selectedImagePath = getPath(selectedImageUri);
             System.out.println("Image Path : " + selectedImagePath);
             System.out.println("Current view : " + current_image_view);
             setPic(selectedImagePath.toString(),current_image_view);
		}else{
			Log.d(TAG, "OnActivityResult: Nothing speacial !!!!");
		}
	}
	
 	public String getPath(Uri uri) {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = managedQuery(uri, projection, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
	  
	private void sendPhoto(Bitmap[] bitmap) throws Exception {
		new UploadTask().execute(bitmap);
	}

	private class UploadTask extends AsyncTask<Bitmap[], Void, Void> {
		
		protected Void doInBackground(Bitmap[]... bitmaps) {
			if (bitmaps[0] == null) // Neu so anh nho hon 3 thi return
				return null;
			setProgress(0);
			int i = 0;
			for(Bitmap bitmap: bitmaps[0]){
				ByteArrayOutputStream stream = new ByteArrayOutputStream();
				bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); // convert Bitmap to ByteArrayOutputStream
				InputStream in = new ByteArrayInputStream(stream.toByteArray()); // convert ByteArrayOutputStream to ByteArrayInputStream
				
				DefaultHttpClient httpclient = new DefaultHttpClient();
				try {
					HttpPost httppost = new HttpPost(Utilities.APP_SERVER_URL_UPLOAD); // server

					MultipartEntity reqEntity = new MultipartEntity();
					reqEntity.addPart("myFile",
							System.currentTimeMillis() + ".jpg", in);
					httppost.setEntity(reqEntity);

					Log.i(TAG, "request " + httppost.getRequestLine());
					HttpResponse response = null;
					try {
						response = httpclient.execute(httppost);
						HttpEntity httpEntity = response.getEntity();
						if(httpEntity != null){
							String result = EntityUtils.toString(httpEntity);
							Log.d(TAG, "Reposnd image path "+result);
							imagePath[i] = result;
							i++;
							// Luu lai duong dan de post len server
						}	
					} catch (ClientProtocolException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					try {
						if (response != null)
							Log.i(TAG, "response " + response.getStatusLine().toString());
					} finally {

					}
				} finally {

				}

				if (in != null) {
					try {
						in.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}

				if (stream != null) {
					try {
						stream.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			return null;
		}
		
		@Override
		protected void onProgressUpdate(Void... values) {
			// TODO Auto-generated method stub
			super.onProgressUpdate(values);
		}
		
		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Log.d(TAG, "Image path count ="+imagePath.length);
			// Upload anh xong se thuc hien post San pham len server
			PostProduct();
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
			pdia = new ProgressDialog(ActivityPostProduct.this);
	        pdia.setMessage("Posting...");
	        pdia.setCanceledOnTouchOutside(false);
	        pdia.show();   
		}
		
		
	}

	private void PostProduct(){
		new PostTask().execute(); // Thuc hien post bai viet len server
		
	}
	private class PostTask extends AsyncTask<Void, Void, String>{

		@Override
		protected String doInBackground(Void... params) {
			// Request len server
			String mes = "Message default";
			JSONArray imagePathJson = new JSONArray();
			for(String value : imagePath)
			{
				imagePathJson.put(value);
			}
			Long tsLong = System.currentTimeMillis()/1000;
			String ts = tsLong.toString();
             try {
             	HttpRequest req = new HttpRequest();
             	List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>();
             	JSONObject product = new JSONObject();
             	product.put("pCategory", 1);
             	product.put("pColor", 1);
             	product.put("pName", edPName.getText().toString().trim());
             	product.put("pSize", edPSize.getText().toString().trim());
             	product.put("pPrice", edPPrice.getText().toString().trim());
             	product.put("pDescription", edPDescription.getText().toString());
             	product.put("pImagePath", imagePathJson);
             	product.put("pOtherInfo", "Thong tin bo sung");
             	product.put("pTimeCreate", ts);
             	nameValuePair.add(new BasicNameValuePair("product",product.toString()));
             	mes = req.makeServiceCall(Utilities.APP_SERVER_URL_INSERT_PRODUCT,HttpRequest.POST,nameValuePair);
             	Log.d(TAG, "Json ="+mes);
             } catch (Exception ex) {
             	ex.printStackTrace();
             }
             return mes;
		}

		@Override
		protected void onPreExecute() {
			// TODO Auto-generated method stub
			super.onPreExecute();
		}

		@Override
		protected void onPostExecute(String result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			pdia.dismiss(); 
			Log.d(TAG,"Server tra ve sau khi nhan du lieu ="+result);
		}
		
		
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		Log.i(TAG, "onResume: " + this);
		
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		// TODO Auto-generated method stub
		super.onConfigurationChanged(newConfig);
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		// TODO Auto-generated method stub
		super.onSaveInstanceState(outState);
		Log.i(TAG, "onSaveInstanceState");
	}

	private void dispatchTakePictureIntent() {
	    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
	    // Ensure that there's a camera activity to handle the intent
	    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
	        // Create the File where the photo should go
	        File photoFile = null;
	        try {
	            photoFile = createImageFile();
	        } catch (IOException ex) {
	            // Error occurred while creating the File

	        }
	        // Continue only if the File was successfully created
	        if (photoFile != null) {
	            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
	            		Uri.fromFile(photoFile));
	            startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
	        }
	    }
	}

	/**
	 * http://developer.android.com/training/camera/photobasics.html
	 */
	private File createImageFile() throws IOException {
	    // Create an image file name
	    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
	    String imageFileName = "JPEG_" + timeStamp + "_";
	    String storageDir = Environment.getExternalStorageDirectory() + "/picupload";
	    File dir = new File(storageDir);
	    if (!dir.exists())
	    	dir.mkdir();   
	    File image = new File(storageDir + "/" + imageFileName + ".jpg");
	    // Save a file: path for use with ACTION_VIEW intents
	    mCurrentPhotoPath = image.getAbsolutePath();
	    Log.i(TAG, "photo path = " + mCurrentPhotoPath);
	    return image;
	}
	
	private void setPic(String path,int imgView) {
		// Get the dimensions of the View
	   int targetW = mImageView1.getWidth();
	   int targetH = mImageView1.getHeight();
	   if(targetW == 0) targetW = 320;
	   if(targetH == 0) targetH = 480;
	    // Get the dimensions of the bitmap
	    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
	    bmOptions.inJustDecodeBounds = true;
	    BitmapFactory.decodeFile(path, bmOptions);
	    int photoW = bmOptions.outWidth;
	    if(photoW == 0) targetW = 320;
	    int photoH = bmOptions.outHeight;
	    if(photoH == 0) targetH = 480;

	    // Determine how much to scale down the image
	    int scaleFactor = Math.min(photoW/targetW, photoH/targetH);

	    // Decode the image file into a Bitmap sized to fill the View
	    bmOptions.inJustDecodeBounds = false;
	    bmOptions.inSampleSize = scaleFactor << 1;
	    bmOptions.inPurgeable = true;

	    Bitmap bitmap = BitmapFactory.decodeFile(path, bmOptions);
	    
	    Matrix mtx = new Matrix();
	    mtx.postRotate(90);
	    // Rotating Bitmap
	    Bitmap rotatedBMP = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mtx, true);

	    if (rotatedBMP != bitmap)
	    	bitmap.recycle();
	    if(imgView == 0){
	    	mImageView1.setImageBitmap(rotatedBMP);
	    	imageBMP[0] = rotatedBMP;
	    }else if(imgView == 1){
	    	mImageView2.setImageBitmap(rotatedBMP);
	    	imageBMP[1] = rotatedBMP;
	    }else if(imgView == 2){
	    	mImageView3.setImageBitmap(rotatedBMP);
	    	imageBMP[2] = rotatedBMP;
	    }
	    
	    // Chi set image, chuc thuc hien viec upload anh
	    
	    /*
	    try {
			sendPhoto(rotatedBMP);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		*/
	}
}
